<template>
  <!-- 智能调度系统 -->
  <el-dialog v-model="store.state.isShowAreaSmartDispatch"
             title="区域模式"
             top="80px"
             :modal="false"
             style="position: absolute;left: 100px;width:20%;"
             :close-on-click-modal="false">
    <el-form :model="selectCityAreaForm">
      <el-form-item label="区域名称" :label-width="formLabelWidth" >
        <el-select v-model="selectCityAreaForm.cityAreaId" placeholder="Please select a bigZone">
          <el-option v-for="item in areaSelect"
                     :label=item.area
                     :value="item.areaId"
                     @click="getCellAreaId(item.areaId)">{{item.area}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理区块" :label-width="formLabelWidth">
        <el-select v-model="selectCityAreaForm.region" placeholder="Please select a zone">
          <el-option v-for="item in cellAreaId"
                     :value ="item">区块{{item}}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" :label-width="formLabelWidth">
        <el-col :span="30">
          <el-form-item prop="startDate">
            <el-date-picker
                v-model="selectCityAreaForm.startDate"
                type="date"
                label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="结束时间" :label-width="formLabelWidth">
        <el-col :span="30">
          <el-form-item prop="endDate">
            <el-date-picker
                v-model="selectCityAreaForm.endDate"
                type="date"
                label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">重置</el-button>
        <el-button  v-show="isShowClearCityArea" @click="ClearSecondArea">清除区域</el-button>
        <el-button type="primary" @click="isShowCheckDialog"
        >查询</el-button
        >
      </span>
    </template>
  </el-dialog>
  <!--区块标识-->
  <div class="traceClass"
       style="position:absolute;
       margin-top: 10px;
       margin-left: 50%;
       z-index: 100;
       background-color: white;
       height: 50px"
       v-show="isShowDisLabel">
    <ul class="traceClassUl" style="margin: 10px; display: flex;">
      <li class="traceClassLi" >
        <div style="background-color: #4ece2b;width: 15px;height: 15px;margin:10px 8px 10px 15px"></div>
        <span class="PolygonStyle_fillType_05" style="margin: auto;font-size: medium">调入站点</span>
      </li>
      <li class="traceClassLi" >
        <div style="background-color: #ce392b;width: 15px;height: 15px;margin:10px 8px 10px 15px"></div>
        <span class="PolygonStyle_fillType_05" style="margin: auto;font-size: medium">调出站点</span>
      </li>
    </ul>
  </div>

  <!--区块详情-->
  <el-dialog  v-model="store.state.isShowAreaXq"
              top="80px"
              class="notice-dialog"
              title="区块详情"
              :modal="false"
              style="position: absolute;right: 40px;width:25%"
              :close-on-click-modal="false">
    <el-form :model="selectCityAreaForm" label-position="top">
      <el-form-item label="区域停车点数据：" :label-width="formLabelWidth">
        <div style=" width: 100%">
          <el-table :data="areaTableData"
                    border style="width: 100%"
                    height="180"
                    :cell-style="{textAlign: 'center'}"
                    @row-click="selectByAttribute">
            <el-table-column prop="id" label="ID" width="50"   />
            <el-table-column prop="date" label="Date"  />
            <el-table-column prop="input" label="流入量"  />
            <el-table-column prop="total" label="流出量"  />
            <el-table-column prop="fangan" label="方案"  />
            <el-table-column prop="address" label="地点" />
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <el-form-item label="供需计算：" :label-width="sformLabelWidth"></el-form-item>
      <el-table :data="inOutData" style="width: 100%">
        <el-table-column prop="Class"  width="150" />
        <el-table-column prop="Data" label="调动情况"></el-table-column>
      </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearLineLayer">清除路线</el-button>
        <el-button type="primary" @click="getSecondDisLineData"
        >计算路线</el-button
        >
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import "../pages/Map.vue";
import store from '../store/index.js'
import {Vector as VectorSource} from "ol/source";
import {Vector as VectorLayer} from "ol/layer";
import {Fill, Stroke, Style,Icon} from "ol/style";
import MultiLineString from "ol/geom/MultiLineString";
import Point from 'ol/geom/Point';
import View from 'ol/View'
import {getCenter} from "ol/extent";
import axios from "axios";
import WKT from "ol/format/WKT";
import { showLoading, hideLoading } from '../store/loading.js'

/**智能调度对话框**/
const isShowClearCityArea=ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '80px'
const sformLabelWidth='100px'
const selectCityAreaForm = reactive({
  cityAreaId:'',
  region: null,
  startDate: '',
  endDate: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})

/**
*第二层调度区域
 * */
/*城市层面的调度*/
const xmSecondDisVector=ref(null)
const xmSecondDisSource=ref(null)
const secondDisFeature=ref(null)
const secondDisFeatureCube=ref([])
const isGetSecondDisData=ref(false)
const secondDisId=ref(1)
//城市区域选择
const areaSelect=reactive([{
  area:'厦门岛',
  areaId:1
  },
  {
    area:'同安区',
    areaId:2
  },
  {
    area:'集美区',
    areaId:3
  },
  {
    area:'翔安区',
    areaId:4
  }
])
//选中城区后，获取城区中的小区域id
const cellAreaId=ref([])
const getCellAreaId=(id)=>{
  cellAreaId.value=[]
  if(id==1){
    for(let i=1;i<=16;i++){
      cellAreaId.value.push(i)
    }
  }else{
    cellAreaId.value=[]
  }
}
//清除区块
const ClearSecondArea=()=>{
  xmSecondDisSource.value.clear()
  xmSecondDisPointSource.value.clear()
  /*隐藏调度标识*/
  isShowDisLabel.value=false
}
const isShowTeissen=ref(false)
//控制Teissen文本注释
const isShowTeissenText=ref(false)
xmSecondDisSource.value=new VectorSource({})
xmSecondDisVector.value =new VectorLayer({
  name2:'区域层面调度',
  source: xmSecondDisSource.value,
  style:function (feature){
    let input= 'rgba(22,243,92,0.5)'
    let output='rgba(241,75,37,0.5)'
    let _color=input
    if(feature.get('bikeRemain')<0){
      _color=output
    }
    return  new Style({
      fill: new Fill({
        color: _color
      }),
      stroke: new Stroke({
        color: 'rgb(0,0,0)',
        width: 1,
      }),
    })
  }
})

/**获取第二层调度区域*/
const getxmSecondCityData=()=> {
  //展示Loading
  showLoading()
  //控制Teisson文本注释显示与隐藏
  isShowTeissenText.value=true;
  secondDisId.value=selectCityAreaForm.region
  console.log(selectCityAreaForm.cityAreaId)
  axios.post(store.state.dbApi + '/secondDispactArea',{areaID:secondDisId.value}).then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetSecondDisData.value)
    {//已获取数据，清空变量
      xmSecondDisSource.value.clear()
      secondDisFeatureCube.value=[]
      //清空表格
      areaTableData.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmSecondDisVector.value)
      //获取图层名字
      console.log(xmSecondDisVector.value.get('name2'))
      store.state.checkDispatchLayerList.push(xmSecondDisVector.value.get('name2'))
      //激活地图点击事件
      //traceCountMsgEvent()
      //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      //createOverlay()
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      secondDisFeature.value=new WKT().readFeature(getData[i]['multipolygon'])
      //设置属性
      secondDisFeature.value.setProperties({
        name:'firstDispatch',
        id:getData[i]['gid'],
        area:getData[i]['area'],
        o_count:getData[i]['o_count'],
        d_count:getData[i]['d_count'],
        bikeRemain:getData[i]['remain'],
        lng:getData[i]['lng'],
        lat:getData[i]['lat'],
        fangan:getData[i]['fangan']
      })
      secondDisFeatureCube.value.push(secondDisFeature.value)
      //为表格添加数据
      areaTableData.value.push({
        id:getData[i]['gid'],
        date:'2020-12-21',
        input:getData[i]['d_count'],
        total:getData[i]['o_count'],
        fangan:getData[i]['fangan'],
        address:getData[i]['lng']+','+getData[i]['lat']
      })
    }
    isGetSecondDisData.value=true
    //将线级加载到图源中
    //隐藏Loading
    hideLoading()
    xmSecondDisSource.value.addFeatures(secondDisFeatureCube.value)
  })

}

/**获取第二层调度站点*/
const xmSecondDisPointVector=ref(null)
const xmSecondDisPointSource=ref(null)
const secondDisPointFeature=ref(null)
const secondDisPointFeatureCube=ref([])
const isGetSecondPointDisData=ref(false)
xmSecondDisPointSource.value=new VectorSource({})
xmSecondDisPointVector.value =new VectorLayer({
  name2:'区域层面调度站点',
  source: xmSecondDisPointSource.value,
  style:new Style({
    image: new Icon({
      scale: 0.08,
      src: "src/assets/站点.svg"
     }),
    })
})
const getxmSecondCityPointData=()=> {
  //展示Loading
  //控制Teisson文本注释显示与隐藏
  isShowTeissenText.value=true;
  secondDisId.value=selectCityAreaForm.region
  console.log(selectCityAreaForm.cityAreaId)
  axios.post(store.state.dbApi + '/secondDisPoint',{areaID:secondDisId.value}).then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetSecondPointDisData.value)
    {//已获取数据，清空变量
      xmSecondDisPointSource.value.clear()
      secondDisPointFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmSecondDisPointVector.value)
      //获取图层名字
      console.log(xmSecondDisPointVector.value.get('name2'))
      store.state.checkDispatchLayerList.push(xmSecondDisPointVector.value.get('name2'))
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      secondDisPointFeature.value=new WKT().readFeature(getData[i]['point'])
      //设置属性
      secondDisPointFeature.value.setProperties({
        name:'secondDispatchPoint',
        id:getData[i]['gid'],
      })
      secondDisPointFeatureCube.value.push(secondDisPointFeature.value)
    }
    isGetSecondPointDisData.value=true
    //将线级加载到图源中
    xmSecondDisPointSource.value.addFeatures(secondDisPointFeatureCube.value)
  })
}

//选中表格对象高亮
/**
 * 根据属性高亮选择要素
 * */
const selectdByAttriFeature=ref(null)
const oldSelectdByAttriFeature=ref(null)
const selectByAttribute=(row)=>{
  let features=xmSecondDisVector.value.getSource().getFeatures();
  let property='id'
  //清除上一个高亮显示
  if(oldSelectdByAttriFeature.value!=null) {
    console.log(oldSelectdByAttriFeature)
    oldSelectdByAttriFeature.value.setStyle(null)
    oldSelectdByAttriFeature.value=null
  }
  for(var i=0,ii=features.length;i<ii;i++){
    if(features[i].get(property)===row.id){
      selectdByAttriFeature.value=features[i];
      break
    }
  }
  oldSelectdByAttriFeature.value=selectdByAttriFeature.value
  selectdByAttriFeature.value.setStyle(
      new Style({
        fill: new Fill({
          color:'rgb(255,255,255,0.4)'
        }),
        stroke: new Stroke({
          color: 'rgb(59,130,229)',
          width: 3,
        }),
      })
  )
  //转到中心点
  let my_view=new View({
    center:getCenter(selectdByAttriFeature.value.getGeometry().getExtent()),
    projection:'EPSG:4326',
    zoom: 16,
  })
  store.state.map.setView(my_view)
}

/**
 *获取第二层调度路线*/
//可视化第一层单车调度路线
const xmSecondDisLineVector=ref(null)
const xmSecondDisLineSource=ref(null)
const secondDisLineFeatureCube=ref([])
const isGetSecondDisLineData=ref(false)
//控制调度路线图层显示与隐藏
const isShowSecondDisLine=ref(true)
xmSecondDisLineSource.value=new VectorSource({})
xmSecondDisLineVector.value=new VectorLayer({
  name2:'区域层面调度路线',
  source: xmSecondDisLineSource.value,
  style:function(feature){
    var myStyle = [];
    myStyle.push(new Style({
      stroke: new Stroke({
        color: '#e8bc57',
        width: 2,
      }),
    }));
    var linearr = feature.getGeometry().getLineStrings();
    console.log(linearr.length)
    for(let i=0;i<linearr.length;i++){
      linearr[i].forEachSegment(function (start,end){
        var arrowLonLat = [end[0] , end[1]];
        var dx = end[0] - start[0];
        var dy = end[1] - start[1];
        var rotation = Math.atan2(dy, dx);
        //箭头图片样式
        myStyle.push(new Style({
          geometry: new Point(arrowLonLat),
          image: new Icon({
            scale: 0.06,
            src: 'src/assets/箭头右.svg',
            rotateWithView: true,
            rotation: -rotation
          })
        }));
      });
    }
    return myStyle;
  }
  /*new Style({
    stroke: new Stroke({
      color: '#e8bc57',
      width: 4,
    })
  })*/
})
//清除路线图层
const clearLineLayer=()=>{
  //清除
  console.log('清除')
  xmSecondDisLineSource.value.clear()
}
/**
 * 获取第二层路网数据*/
const getSecondDisLineData=()=> {
  //展示Loading
  showLoading()
  axios.post(store.state.dbApi + '/secondDisLine',{areaID:secondDisId.value}).then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetSecondDisLineData.value)
    {//已获取数据，清空变量
      xmSecondDisLineSource.value.clear()
      secondDisLineFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmSecondDisLineVector.value)
      store.state.checkDispatchLayerList.push(xmSecondDisLineVector.value.get('name2'))
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      secondDisLineFeatureCube.value.push(new WKT().readFeature(getData[i]['multiline']))
      console.log(getData[i]['multiline'])
    }
    //隐藏Loading
    hideLoading()
    //将线级加载到图源中
    xmSecondDisLineSource.value.addFeatures(secondDisLineFeatureCube.value)
    isGetSecondDisLineData.value=true
  })
}


/**
 * 智能调度区域详情
 * */
/*控制查询结果对话框显示隐藏*/
const isShowDisLabel=ref(false)
const isShowCheckDialog=()=> {
  /*加载第二层调度区域*/
  getxmSecondCityData()
  /*加载第二层调度站点*/
  setTimeout(function (){getxmSecondCityPointData()},900)
  /*显示按钮*/
  isShowClearCityArea.value=true;
  /*显示调度标识*/
  isShowDisLabel.value=true
  let isShow = store.state.isShowAreaXq
  if (isShow === true) {
    store.commit('changeIsShowAreaXq', false)
  } else {
    store.commit('changeIsShowAreaXq', true)
  }
}

//表格
const areaTableData =ref([])

//供需表格
const inOutData=ref([])
inOutData.value.push(
    {
      Class:'调入站点数',
      Data:16
},{
      Class:'调出站点数',
      Data:13
    }
)
</script>
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

</style>
